package com.lynn.accesstoken.interceptor;

import com.lynn.accesstoken.bean.AppEntity;
import com.lynn.accesstoken.redis.RedisManager;
import com.lynn.accesstoken.repo.AppEntityRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AccessTokenInteceptor
 * @Description TODO
 * @Author ly
 * @Date 2019-05-30 21:02
 * @Version 1.0
 */
@Slf4j
@Component
public class AccessTokenInteceptor implements HandlerInterceptor {

    private RedisManager redisManager;

    private AppEntityRepo appEntityRepo;

    public AccessTokenInteceptor(RedisManager redisManager, AppEntityRepo appEntityRepo) {
        this.redisManager = redisManager;
        this.appEntityRepo = appEntityRepo;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        log.info("进入拦截器");
        System.out.println("token:" + token);
        if (StringUtils.isEmpty(token)) {
            log.info("token不存在");
            return false;
        }
        String appId = (String) redisManager.get(token);
        if (StringUtils.isEmpty(appId)) {
            log.info("appid 不存在");
            return false;
        }
        AppEntity appEntity = appEntityRepo.findByAppId(appId);
        if (appEntity == null) {
            log.info("app 不存在");
            return false;
        }
        if (appEntity.getFlag() == 0) {
            log.info("app 不生效");
            return false;
        }
        return true;
    }

}
